#include "raytracer.h"

#include "stdio.h"
#include "string.h"

// IMAGE FILE HEADERS ---------------------------------------------------------------
#define PPMv6 "P6\n\n%i %i\n255\n" 			// PPM v6 -> supports: RGB8

// FUNCTIONS ------------------------------------------------------------------------

// write a framebuffer to disk in a given image format
void imageWrite(const framebuffer *f,	// source frame buffer for dump-to-disk
                imageType type,			// output image type
                const char* filename)   // filename of the output image
{
	NULL_GUARD(f);
	NULL_GUARD(f->buffer);
	NULL_GUARD(filename);
	
	// fail if:
	ASSERT_GUARD((unsigned int)type < IMAGETYPE_EOL, "type:%i\n", type); // invalid image type is given

	// get space for the image file-header
	unsigned char fileHeader[120];
	memset(fileHeader, 0, sizeof(unsigned char));

	// byte size of a single pixel for writing
	int byteSize = -1; 
	
	// now check which image type to write and set the fileheader accordingly
	switch(type)
	{
	  case PPM:
			if (f->type != RGB8) // PPM v6 is only compatible with RGB8 framebuffers
			{
			  printf("ERROR: PPMv6 can only convey an RGB8 framebuffer. image was NOT written.\n");
			  return;
			};
			sprintf(fileHeader, PPMv6, f->width, f->height);  // write file-header to buffer
			byteSize = sizeof(pixelRGB8);                     // set correct pixel byte size

	    break;
	}

	// open up a new image file in "overwrite" mode
	FILE *file = fopen(filename,"wb");
	NULL_GUARD(file);

	fprintf(file, "%s", fileHeader);  						// write the fileheader
 	fwrite(f->buffer, byteSize, f->width*f->height, file);  // write pixels from the framebuffer

	// close newly created image file
 	fclose(file);
};
